import 'dart:convert';

import 'dart:math';
import 'package:flutter/widgets.dart';

///
///@description
///字符串帮助类
///@author: Murphy
///@create: 2021-08-20 11:41
///
class StringUtils {
  static bool isEmpty(String str) {
    if (str.isEmpty) {
      return true;
    }
    return false;
  }

  ///正则验证是否http地址
  static bool isHttp(String value) {
    // return RegExp(r"^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+").hasMatch(value);
    return RegExp(r"^((https|http)?:\/\/)[^\s]+").hasMatch(value);
  }

  ///Base64加密
  static String encodeBase64(String data) {
    var content = utf8.encode(data);
    var digest = base64Encode(content);
    return digest;
  }

  ///Base64解密
  static String decodeBase64(String data) {
    return String.fromCharCodes(base64Decode(data));
  }

  ///限制字符串长度 替换...
  static String limitStringLength(
    String str,
    int length,
  ) {
    if (str.contains('\n')) {
      str = str.replaceAll("\n", "");
    }
    if (str.length > length && length > 2) {
      str = '${str.characters.getRange(0, length - 2).string}...';
    }
    return str;
  }

  //计算字符长度(目前只支持汉字,数字,字母)
  static int textCharLength(String text) {
    int count = 0;
    final chinaReg = RegExp(r'^[\u4e00-\u9fa5]+$');      //汉字
    final otherReg = RegExp('[a-zA-Z]|[0-9]|[-_]');      //字母,数字,-_
    for (int i = 0; i < text.length; i++) {
      String character = text.substring(i, i+1);
      if (chinaReg.hasMatch(character)) {
        print('character = $character, 2');
        count += 2;
      } else if (otherReg.hasMatch(character)) {
        print('character = $character, 1');
        count += 1;
      }
    }
    return count;
  }

  ///生成固定长度随机字符串
  ///strlenght 生成的字符串固定长度
  static String sendRandomStr({int strlenght = 9}){
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    String left = '';
    for (var i = 0; i < strlenght; i++) {
//    right = right + (min + (Random().nextInt(max - min))).toString();
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

  String formatlargeNumber(String str) {
    if (str.length > 4) {
      return "${str.substring(0, str.length - 4)}w";
    }
    if (str.length > 3) {
      return "${str.substring(0, str.length - 3)}k";
    }
    return str;
  }

  ///计算Text文本的宽高
  static Size boundingTextSize(BuildContext context, String text, TextStyle style,  {int maxLines = 2^31, double maxWidth = double.infinity}) {
    if (text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        locale: Localizations.localeOf(context),
        text: TextSpan(text: text, style: style), maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }
}

extension Helper on String {
  String get joinZeroWidthSpace => Characters(this).join("\u{200B}");
}
